var rootPath = getRootPath();

$(function() {
	//滚动条置顶
	$("body").prepend('<input type="text" id="focus" size="1">');
    $("#focus").focus();
    $("#focus").hide();
    
	var rleId = getUrlParam("rleId");
	if(rleId == '') {
		layer.alert("认证出错,请求参数有误:)");
	}
	$("#rleId").val(rleId);
	var prevPage = getUrlParam("currentPage");
	
	//===========address 三级联动  start==============
	// 地址选择器遮罩层打开与关闭
	$("#areaLabel").click(function(e){
	    $("#addressSelectWrapper").show();
	    e.stopPropagation();
	});
	$(document).click(function () {
        $("#addressSelectWrapper").hide();
    });
	$("#cancel").click(function () {
        $("#addressSelectWrapper").hide();
    });
    $("#addressSelect").click(function (e) {
		e.stopPropagation();
    });
    initAddress();
  //===========address 三级联动  end==============
	
	//form1  身份 回显部分
	$.ajax({
		url: rootPath + '/verify/uid/rleId/' + rleId + '/dr/1',
		type: 'GET',
		success: function(data) {
			if(data.returnCode == '0000') {
				var obj = data.returnObject;
				//sid = obj.school.sid;
				//$("#school").find("option[value='" + sid + "']").prop("selected","selected");
				var education = obj.education;
				$("#education").find("option[value='" + education + "']").prop("selected","selected");
				getEnrollmentYear();
				var enrollmentYear = obj.enrollmentYear;
				$("#enrollmentYear").find("option[value='" + enrollmentYear + "']").prop("selected","selected");
				if(obj.phone){
					$("#phone").val(obj.phone);
				}
				if(obj.email){
					$("#email").val(obj.email);
					$("#email").prop("disabled",true);
				}
				
				$("#wechat").val(obj.wechat);
				$("#intro").val(obj.intro);
			}else if("2001" == data.returnCode){
				//getUserPhoneAndEmail();
			}else {
				layer.alert("errorCode:"+date.returnCode);
			}
 
		},error: function (jqXHR, textStatus, errorThrown) {
    		layer.alert("error:(");
    	}
	});
	//form2 收货地址回显 部分
	
	
	//学校选择部分
	setTimeout(function(){
	$("#school").select2({
		ajax:{
			type: 'POST',
			url: rootPath + '/solr/schoolSearch',
			delay: 250,
			data: function (params) {
		          return {
		            text: params.term, // search term 请求参数
		            page: params.page
		          };
		        },
	        processResults: function (data, params) {
	            params.page = params.page || 1;
	            var srcList = data.returnCode=="0000"?data.returnObject:[];
	            var desList = [];
	            var temp;
	            for(var i=0;i<srcList.length;i++){
	            	temp = {};
	            	temp.id=srcList[i].id;
	            	temp.text=srcList[i].title[0];
	            	desList[i]=temp;
	            }
	            
	            return {
	              results: desList,//itemList
	              pagination: {
	                more: (params.page * 2) < data.total_count
	              }
	            };
	          },
	          cache: true
	        },
	        placeholder:'请选择学校',//默认文字提示
	        language: "zh-CN",
	        tags: false,//允许手动添加
	        allowClear: true,//允许清空
	        escapeMarkup: function (markup) { return markup; }, // 自定义格式化防止xss注入
	        minimumInputLength: 2,
	        formatResult: function formatRepo(repo){return repo.text;}, // 函数用来渲染结果
	        formatSelection: function formatRepoSelection(repo){return repo.text;} // 函数用于呈现当前的选择
	});
	},50);
	
	$("#intro").bind("change,keydown,up", function() {
		$(this).val($(this).val().substring(0,800));
	});
	
	//上一步
	$("#prev").click(function() {
		var creType = $("#sort").val();
		parent.$("#content").prop("src", prevPage + "?rleId=" + rleId + "&creType=" + creType);
	});
	
	$("#applyAuth").click(function() {
		if(!checkData()){
			return;
		}
		
		var studentAuthForm = $('#studentAuthForm').serializeJson();
		var userAddressForm = $('#userAddressForm').serializeJson();
		
		studentAuthForm.userAddress = userAddressForm;
		
		
		//简介
		if($("#intro").val().length > 800) {
			$("#intro").focus();
			showErrMsg("intro", "简介输入太长,请精简")
			return;
		}
		
		showLoading();
		$("#studentAuthForm").ajaxSubmit({
			url : rootPath + '/verify/saveOrUpdateVerify',
			type: 'POST',
			contentType : 'application/json;charset=UTF-8',
			success : function(data) {
				hideLoading();
				if(data.returnCode == '0000'){
					layer.msg("操作成功",{icon:1,time:1000},function() {						
						parent.$("#content").prop("src","applyResult.html?rleId=" + rleId + "&title=学生认证");
					});
				}else{
					layer.alert(data.returnMessage);
				}
			},
			error: function (jqXHR, textStatus, errorThrown) {
				hideLoading();
				layer.alert("error");
			}
		});
		return false;
	});
});

function checkData(){
	var sid=$("#school option:selected").val();
	if($.trim(sid) == '') {
		$("#school").focus();
		showErrMsg("school","请选择学校");
		return false;
	}
	var education=$("#education option:selected").val();
	if($.trim(education) == '') {
		$("#education").focus();
		showErrMsg("education","请选择学历");
		return false;
	}
	var enrollmentYear=$("#enrollmentYear option:selected").val();
	if($.trim(enrollmentYear) == '') {
		$("#enrollmentYear").focus();
		showErrMsg("enrollmentYear","请选择入学年份");
		return false;
	}
	
 
	if($.trim($("#intro").val()) == '') {
		$("#intro").focus();
		showErrMsg("intro","请输入简介");
		return false;
	}
	return true;
}
/**
 * 根据年级 联动 入学年份
 * @returns
 */
function getEnrollmentYear(){
	$("#enrollmentYear  option:gt(0)").remove();
	$("#enrollmentYear option:first").prop('selected', 'selected');
	var education = $("#education").val();
	var currentYear = parseInt(new Date().getFullYear());
	var option = "";
	switch(education){
	case"P":	//小学
		option = "";
		for(var i=currentYear-6;i<=currentYear;i++){
			option += "<option value=\""+i+"\">"+ i +"</option>"
		} 
		$(option).appendTo($("#enrollmentYear"));
		break;
	case "J":   //初中
	case "H":	//高中
		option = "";
		for (var i = currentYear - 3; i <= currentYear; i++) {
			option += "<option value=\""+i+"\">"+ i +"</option>"
		}
		$(option).appendTo($("#enrollmentYear"));
		break;
	}
}
/**
 * 初始化地址三级联动
 * @returns
 */
function initAddress() {
    $("#Addr").cityLinkage({
        containerId: 'addressSelectWrapper',
        getSelectedCode:function(){return $("#Addr").data("code");},
        callback:function(data) {
			$("#provinceName").val(data.province.name);
			$("#cityName").val(data.city.name);
			$("#countryName").val(data.area.name);
			
            $("#Addr").val(data.addr).data("code",data.area.code);
        }
    });
}

/*function getUserPhoneAndEmail(){
	$.ajax({
		url: rootPath + '/user/queryUserself',
        type: 'GET',
        contentType: 'application/json;charset=UTF-8',
        success: function (data) {
        	if(data.returnCode == '0000') {
        		var user = data.returnObject;
        		var phone = user.phone;
        		var email = user.email;
        		//手机号码后台已用*替换
        		if(phone){
					$("#phone").val(phone);
					$("#phone").prop("disabled",true);
				}
				if(email){
					$("#email").val(email);
					$("#email").prop("disabled",true);
				}
        	}
        },
        error: function (jqXHR, textStatus, errorThrown) {
        	layer.alert("error");
        }
    });
}*/